import { loginApi, getInfoApi } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
const state = {
  // 初始化：从cookie中去读取token
  token: getToken(),
  // 用户资料
  userInfo: {} // userId  username
}
const mutations = {
  // 设置token
  setToken(state, data) {
    state.token = data // 存state
    setToken(data) // 存cookie
  },
  // 删除token
  removeToken(state) {
    state.token = null
    removeToken()
  },
  // 设置用户资料
  setUserInfo(state, data) {
    state.userInfo = data
  },
  // 删除用户资料
  removeUserInfo() {
    state.userInfo = {}
  }
}
const actions = {
  // 登录的action==> 页面中 this.$store.dispatch('user/loginAction',表单数据)
  async loginAction(context, data) {
    const res = await loginApi(data)
    context.commit('setToken', res)
  },
  // 获取用户资料的action
  async getUserProfileAction(context) {
    const res = await getInfoApi()
    res.roles.points = ['employee-add', 'employee-see', 'employee-import']
    context.commit('setUserInfo', res)
    return res
  },
  // 退出操作
  logout({ commit }) {
    // 移除token
    commit('removeToken')
    // 清除用户资料
    commit('removeUserInfo')
    // 重置路由
    resetRouter()
    // vuex的user模块action里面调用permission模块的mutations方法
    commit('permission/setRoutes',[],{root:true})
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

